//
//  AppDelegate.m
//  WanCaiC8
//
//  Created by tangang on 2017/12/29.
//  Copyright © 2017年 tangang. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarViewController.h"
#import "HomeVC.h"
#import <AlipaySDK/AlipaySDK.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import "ShareHelper.h"
#import "JPEngine.h"
#import <AdSupport/AdSupport.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "BaiduMobStat.h"
#import <UMCommon/UMCommon.h>
//#import <UMAnalytics/DplusMobClick.h>
#import <UMCommonLog/UMCommonLogHeaders.h>
#import <UMAnalytics/MobClick.h>

static NSString *JpushAppKey = @"dd98d336c58509358f83389c";




//盈彩网 5c3c7d1bf1f556ed5900028c 旺角 5c3c7d8bb465f5915200030d 天下彩客 5c3c7daff1f556c42600035c 彩霸网 5c3c7de4b465f591c1000322 六彩网 5c3c7e07b465f5925d00034f
//盈彩网
static NSString *UMKey =@"5c3c7d1bf1f556ed5900028c";

@interface AppDelegate ()<WXApiDelegate>
@property (nonatomic ,strong) TencentOAuth *tencentOAuth;
@end

@implementation AppDelegate

// 启动百度移动统计
//- (void)startBaiduMobileStat{
//    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
//    statTracker.enableDebugOn = YES;
//    statTracker.logSendWifiOnly=YES;
//    [statTracker startWithAppId:BaiDuKey]; // 设置您在mtj网站上添加的app的appkey,此处AppId即为应用的appKey
//}

///热更新
- (void)hotUpdate{
    [JPEngine startEngine];
    NSString *script=[NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://c8-public.oss-cn-shenzhen.aliyuncs.com/client/Ios/wancaiba.js"] encoding:NSUTF8StringEncoding error:nil];
    if (!script) {
        return;
    }
    [JPEngine evaluateScript:script];
}

-(void)setUM{
    
    [UMConfigure initWithAppkey:UMKey channel:@"App Store"];
    /** 设置是否在console输出SDK的log信息.
     @param bFlag 默认NO(不输出log); 设置为YES, 输出可供调试参考的log信息. 发布产品时必须设置为NO.
     */
    [UMConfigure setLogEnabled:YES];//设置打开日志
    
    /** 开启CrashReport收集, 默认YES(开启状态).
     @param value 设置为NO,可关闭友盟CrashReport收集功能.
     @return void.
     */
    [MobClick setCrashReportEnabled:YES];
    /** 设置是否对统计信息进行加密传输, 默认NO(不加密).
     @param value 设置为YES, umeng SDK 会将日志信息做加密处理
     */
    [UMConfigure setEncryptEnabled:YES];
    
    NSString* deviceID =  [UMConfigure deviceIDForIntegration];
    NSLog(@"集成测试的deviceID:%@",deviceID);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    [self startBaiduMobileStat];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self setUM];
        [WXApi registerApp:WXKEY enableMTA:NO];
        _tencentOAuth = [[TencentOAuth alloc] initWithAppId:TXKEY andDelegate:[ShareHelper share]];
    });
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    HomeVC *vc=[[HomeVC alloc]init];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:vc];
    self.window.rootViewController=nav;
    [self.window makeKeyAndVisible];
    

//    TabBarViewController *tabVC=[[TabBarViewController alloc]init];
////
//    [self hotUpdate];
  
    

    
   
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {

}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }else if ([url.host isEqualToString:@"response_from_qq"]){
        return [QQApiInterface handleOpenURL:url delegate:[ShareHelper share]];
        
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSInteger resultStatus =[[resultDic objectForKey:@"resultStatus"] integerValue];
            if (resultStatus==9000) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:@"支付结果：成功！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:@"支付结果：失败！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            
        }];
    }else if ([url.host isEqualToString:@"response_from_qq"]){
        return [QQApiInterface handleOpenURL:url delegate:[ShareHelper share]];
        
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg;
        switch (resp.errCode) {
            case WXSuccess:
            {
                strMsg = @"支付结果：成功！";
//                [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:pay_notice object:nil userInfo:nil]];
            }
                break;
            case WXErrCodeUserCancel:
                strMsg=@"用户取消支付";
                break;
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
        [SVProgressHUD showSuccessWithStatus:strMsg];
    }else if([resp isKindOfClass:[SendAuthResp class]]) {
//        SendAuthResp* authResp = (SendAuthResp*)resp;
        switch (resp.errCode) {
            case WXSuccess:
            {
//                LoginVC *vc=(LoginVC *)self.window.rootViewController;
//                [vc setWXCode:authResp.code];
            }
                break;
            case WXErrCodeAuthDeny:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
                break;
            case WXErrCodeUserCancel:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败" message:@"用户取消登录" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            default:
                break;
        }
    }else if ([resp isKindOfClass:[SendMessageToWXResp class]]){
        switch (resp.errCode) {
            case WXSuccess:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享成功" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
                break;
            case WXErrCodeAuthDeny:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
                break;
            case WXErrCodeUserCancel:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"取消分享" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            default:
                break;
        }
    }
}


@end
